package com.tongzhan.service.impl;

import com.tongzhan.base.PageInfo;
import com.tongzhan.base.Return;
import com.tongzhan.data.vo.ReportUsualVO;
import com.tongzhan.data.vo.UnReportedSiteVO;
import com.tongzhan.data.vo.UsualDetailVO;
import com.tongzhan.entity.User;
import com.tongzhan.entity.religion.ModuleSign;
import com.tongzhan.entity.religion.SiteInfo;
import com.tongzhan.entity.religion.Usual;
import com.tongzhan.entity.religion.UsualTask;
import com.tongzhan.repository.UserRepository;
import com.tongzhan.repository.religion.ModuleSignRepository;
import com.tongzhan.repository.religion.SiteInfoRepository;
import com.tongzhan.repository.religion.UsualRepository;
import com.tongzhan.repository.religion.UsualTaskRepository;
import com.tongzhan.service.UsualService;
import com.tongzhan.utils.DateSwitcher;
import com.tongzhan.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class UsualServiceImpl implements UsualService {

    @Autowired
    private SiteInfoRepository siteInfoRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private UsualRepository usualRepository;

    @Autowired
    private UsualTaskRepository usualTaskRepository;

    @Autowired
    private ModuleSignRepository signRepository;

    @Override
    public Return everydayReport(String userId) {
        LocalDate now = LocalDate.now();
        //今日需报送任务的列表
        List<UsualTask> taskList = usualTaskRepository.findAll(new Query()
                .addCriteria(Criteria.where("StartTime")
                        .lte(now).and("EndTime").gte(now)));
        if (CollectionUtils.isEmpty(taskList)) {
            return new Return(Return.FAIL, "无报送任务需要报送");
        }
        for (UsualTask task : taskList) {
            //用户信息
            User user = userRepository.findByPrimaryKey(userId);
            String usualCode = task.getUsualCode();
            Query query = new Query();
            Criteria c = Criteria.where("RealName")
                    .is(user.getRealName()).and("UsualCode").is(usualCode);
            query.addCriteria(c);
            //报送列表
            List<Usual> usualList = usualRepository.findAll(query);
            Usual usual = null;
            if (!CollectionUtils.isEmpty(usualList)) {
                //获取当日的报送情况
                for (Usual u : usualList) {
                    LocalDate time = u.getTime().toLocalDate();
                    if (time.compareTo(now) == 0) {
                        usual = u;
                        break;
                    }
                }
            }
            if (usual == null) {
                Usual todayUsual = new Usual();
                todayUsual.setUsualCode(usualCode);
                todayUsual.setUserTitle(task.getTitle());
                todayUsual.setRealName(user.getRealName());
                todayUsual.setSiteCode(user.getSiteCode());
                todayUsual.setSiteName(user.getSiteName());
                todayUsual.setStreetCode(user.getStreetCode());
                todayUsual.setStreetName(user.getStreetName());
                todayUsual.setReligionCode(user.getReligionCode());
                todayUsual.setReligionName(user.getReligionName());
                todayUsual.setState("平安");
                todayUsual.setTime(LocalDateTime.now());
                usualRepository.insert(todayUsual);
            }
        }
        //平安报送成功，重置平安报送角标
        ModuleSign sign = signRepository.findByPrimaryKey(userId);
        if (sign != null) {
            sign.setUsual(0L);
            signRepository.updateByPrimaryKey(sign);
        }
        return new Return(Return.SUCCESS, "操作成功");
    }

    @Override
    public Return usualDetails(String userId, String usualCode, String siteCode, Integer page, Integer size) {
        User user = userRepository.findByPrimaryKey(userId);
        if (user == null) {
            return new Return(Return.FAIL, "用户不存在");
        }
        Query query = new Query();
        query.addCriteria(Criteria.where("UsualCode").is(usualCode))
                .with(Sort.by(Sort.Direction.DESC, "Time"));
        //获取当前登录用户信息
        ThreadLocalUtil.AdminThreadLocal threadLocal = ThreadLocalUtil.getThreadLocal();
        //权限编码
        String dutiesCode = threadLocal.getDutiesCode();
        if (ThreadLocalUtil.STREET_CODE.equals(dutiesCode)) {
            //镇街道
            query.addCriteria(Criteria.where("StreetCode").is(threadLocal.getStreetCode()));
        } else if (ThreadLocalUtil.VILLAGE_CODE.equals(dutiesCode)) {
            //村社区
            query.addCriteria(Criteria.where("VillageCode").is(threadLocal.getVillageCode()));
        }
        if ("04".equals(user.getDutiesCode()) || "07".equals(user.getDutiesCode())) {
            //宗教场所、民间信仰点
            query.addCriteria(Criteria.where("SiteCode").is(siteCode));
        } else {
            if (StringUtils.isNotEmpty(siteCode)) {
                query.addCriteria(Criteria.where("SiteCode").is(siteCode));
            }
        }
        //不带分页查询总记录
        List<Usual> allUsualList = usualRepository.findAll(query);
        //只查询出平安状态
        query.addCriteria(Criteria.where("State").is("平安"));
        Page<Usual> usuals = usualRepository.findPage(query, PageRequest.of(page - 1, size));
        List<Usual> usualList = usuals.getContent();
        //返回数据VO
        UsualDetailVO detailVO = new UsualDetailVO();
        List<ReportUsualVO> usualVOS = new ArrayList<>();
        //总计上报
        int totalReported = 0;
        //总计未报送
        int totalUnReported = 0;
        for (Usual usual : allUsualList) {
            //报送状态
            String state = usual.getState();
            if ("平安".equals(state)) {
                totalReported++;
            } else {
                totalUnReported++;
            }
        }
        if (!CollectionUtils.isEmpty(usualList)) {
            for (Usual u : usualList) {
                //报送信息
                ReportUsualVO usualVO = new ReportUsualVO();
                usualVO.setRealName(u.getRealName());
                usualVO.setState(u.getState());
                usualVO.setTime(u.getTime());
                usualVO.setSiteName(u.getSiteName());
                usualVOS.add(usualVO);
            }
        }
        detailVO.setTotalReported(totalReported);
        detailVO.setTotalUnReported(totalUnReported);
        detailVO.setDetailList(usualVOS);
        PageInfo pageInfo = new PageInfo();
        pageInfo.setPage(page);
        pageInfo.setSize(usualVOS.size());
        pageInfo.setTotal(usuals.getTotalElements());
        detailVO.setPageInfo(pageInfo);
        return new Return(detailVO);
    }

    @Override
    public Return showNotReported(LocalDate date) {
        //查询指定日期有无报送任务
        List<UsualTask> taskList
                = usualTaskRepository.findAll(new Query().addCriteria(Criteria.where("StartTime").lte(date)
                .and("EndTime").gte(date)));
        //封装VO
        List<UnReportedSiteVO> siteVOS = new ArrayList<>();
        if (!CollectionUtils.isEmpty(taskList)) {
            //有报送任务
            Query query = new Query();
            query.with(Sort.by(Sort.Direction.ASC, "ReligionCode"));
            query.addCriteria(Criteria.where("Jurisdiction").is("是"));//受管辖的场所
            //场所列表
            List<SiteInfo> siteInfos = siteInfoRepository.findAll(query);
            if (!CollectionUtils.isEmpty(siteInfos)) {
                for (SiteInfo info : siteInfos) {
                    //查询条件
                    Query search = new Query();
                    search.addCriteria(Criteria.where("SiteCode").is(info.getSiteCode()));
                    search.addCriteria(Criteria.where("Time").gt(DateSwitcher.getMinTime(date.atStartOfDay()))
                            .andOperator(Criteria.where("Time").lt(DateSwitcher.getMaxTime(date.atStartOfDay()))));
                    //报送列表
                    List<Usual> usualList = usualRepository.findAll(search);
                    if (CollectionUtils.isEmpty(usualList)) {
                        UnReportedSiteVO siteVO = new UnReportedSiteVO();
                        siteVO.setSiteCode(info.getSiteCode());
                        siteVO.setSiteName(info.getSiteName());
                        siteVO.setReligionCode(info.getReligionCode());
                        siteVO.setReligionName(info.getReligionName());
                        siteVOS.add(siteVO);
                    }
                }
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("unSubmittedList", siteVOS);
        return new Return(map);
    }

    @Override
    public List<Usual> selectByUsualCode(String usualCode) {
        //查询条件
        Query query = new Query();
        //获取前一天时间
        LocalDateTime last = LocalDateTime.now().minusDays(1);
        //前一天的开始
        LocalDateTime start = DateSwitcher.getMinTime(last);
        //前一天的结尾
        LocalDateTime end = DateSwitcher.getMaxTime(last);
        query.addCriteria(Criteria.where("Time").gte(start).andOperator(Criteria.where("Time").lte(end)));
        query.addCriteria(Criteria.where("UsualCode").is(usualCode));
        //报送列表
        List<Usual> usualList = usualRepository.findAll(query);
        if (CollectionUtils.isEmpty(usualList)) {
            return new ArrayList<>();
        }
        return usualList;
    }

    @Override
    public void insert(Usual usual) {
        usualRepository.insert(usual);
    }

    @Override
    public Return usualReminder(String siteCodes) {
        String[] codeArr = siteCodes.split(",");
        for (String siteCode : codeArr) {
            //获取模块标识信息
            ModuleSign sign = signRepository.findOne(new Query().addCriteria(Criteria.where("SiteCode").is(siteCode)));
            if (sign != null) {
                //平安报送角标加一
                sign.setUsual(sign.getUsual() + 1);
                signRepository.updateByPrimaryKey(sign);
            }
        }
        return new Return(Return.SUCCESS, "一键提醒成功");
     }
}
